package com.ddstation.onsitelaw.controller;

import com.ddstation.onsitelaw.entity.DtHealthManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.DtInvsManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.DtSupervisorEnforcementEntity;
import com.ddstation.onsitelaw.model.AccountModel;
import com.ddstation.onsitelaw.model.DtPrescriptionTemplateManageModel;
import com.ddstation.onsitelaw.model.HealthInstitutionModel;
import com.ddstation.onsitelaw.service.DataImportService;
import com.ddstation.onsitelaw.service.DtHealthManageInstitutionService;
import com.ddstation.onsitelaw.service.DtInvsManageInstitutionService;
import com.ddstation.onsitelaw.utils.AliCloudOssUtil;
import com.ddstation.onsitelaw.utils.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author 陆青龙
 */
@Controller
public class InstitutionalInfoController {

    private static final Logger logger = LoggerFactory.getLogger(InstitutionalInfoController.class);

    @Inject
    private DtHealthManageInstitutionService dtHealthManageInstitutionService;


    @Inject
    private DtInvsManageInstitutionService invsManageInstitutionService;


    @Inject
    private DataImportService dataImportService;

    /**
     * 跳转违规查询页
     */
    @RequestMapping(value = "institutionalInfo")
    String violationQuery(HttpSession session, Model model) {
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            model.addAttribute("code", -1);
            model.addAttribute("msg", "登录状态已失效，请重新登录!");
        }

        model.addAttribute("county", account.getManageInstitutionEntity().getCounty());

        DtInvsManageInstitutionEntity entity = account.getManageInstitutionEntity();
        List<DtInvsManageInstitutionEntity> regionList = invsManageInstitutionService
                .selectByAddress(entity.getProvince(), entity.getCity(), entity.getCounty());

        model.addAttribute("regionList", regionList);
        List<DtPrescriptionTemplateManageModel> prescriptionTemplates = dtHealthManageInstitutionService.selectPrescriptionTemplate(null, null);
        model.addAttribute("prescriptionTemplates", prescriptionTemplates);
        return "institutionalInfo";
    }


    @RequestMapping("institutionalInfo/institutionalInfoList")
    @ResponseBody
    Map<String, Object> institutionalInfoList(
            HttpSession session,
            @RequestParam String institutionalName,
            @RequestParam String pageNum,
            @RequestParam String pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        List<String> healthManageInstitutionIds = null;
        if (account.getRoleId() == 1) {
            List<DtHealthManageInstitutionEntity> healthManageList = account.getDtHealthManageInstitutionEntityList();
            healthManageInstitutionIds = healthManageList.stream().map(i -> i.getId()).collect(Collectors.toList());
        }
        if (account.getRoleId() == 2) {
            List<DtSupervisorEnforcementEntity> supervisorEnforcements = account.getEnforcementList();
            healthManageInstitutionIds = supervisorEnforcements.stream().map(i -> i.getHealthManageId()).collect(Collectors.toList());
        }
        HashMap paramMap = new HashMap();
        paramMap.put("institutionIdList", healthManageInstitutionIds);
        paramMap.put("institutionalName", institutionalName);
        paramMap.put("pageNum", pageNum);
        paramMap.put("pageSize", pageSize);
        PageResult pageResult = dtHealthManageInstitutionService.getHealthManageList(paramMap);
        map.put("selectHealthManageList", pageResult.getRows());
        map.put("totalNum", pageResult.getTotal());
        map.put("pages", pageResult.getPages());
        map.put("errCode", 1);
        map.put("errMsg", "成功");
        return map;
    }


    @RequestMapping("institutionalInfo/saveInstitutionalInfo")
    @ResponseBody
    Map<String, Object> saveInstitutionalInfo(
            HttpSession session, @RequestBody HealthInstitutionModel healthInstitutionModel) {

        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");

        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        dtHealthManageInstitutionService.saveInstitutionalInfo(healthInstitutionModel);
        List<Integer> templateIds = healthInstitutionModel.getTemplateIds();
        for (Integer templateId : templateIds) {
            DtPrescriptionTemplateManageModel model = dtHealthManageInstitutionService.selectPreTempByPrimaryKey(templateId);
            model.setInstitutionId(healthInstitutionModel.getInstitutionalId());
            model.setId(null);
            dtHealthManageInstitutionService.savePrescriptionTemplate(model);
        }
        map.put("errCode", 1);
        map.put("errMsg", "成功");
        return map;
    }


    /**
     * 处方模板
     */
    @RequestMapping(value = "institutionalInfo/savePrescriptionTemplate")
    @ResponseBody
    Map<String, Object> savePrescriptionTemplate(HttpSession session, @RequestParam("file") MultipartFile file, @RequestParam("templateSign") String templateSign, @RequestParam("templateName") String templateName) throws IOException {

        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "处方模板上传成功！");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");

        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            map.put("errMsg", "服务器繁忙，请稍后再试。");
            return map;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());
        //保存路径：prescription/yyyyMMdd/机构id/图片文件
        String prescriptionDir = "prescriptionTemplate/" + today + "/" + account.getInstitutionId();
        String outpath = System.getProperty("user.dir") + prescriptionDir;
        File localFile = new File(outpath);
        if (!localFile.isDirectory()) {
            localFile.mkdirs();
        }
        localFile = new File(localFile, file.getOriginalFilename());
        file.transferTo(localFile);
        // 阿里云上传 object key
        String ossKey = prescriptionDir + "/" + file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 上传 阿里云 oss
        AliCloudOssUtil.putOSSObject(null, ossKey, localFile);

        DtPrescriptionTemplateManageModel model = new DtPrescriptionTemplateManageModel();
        model.setName(templateName);
        model.setTemplateSign(templateSign);
        model.setTemplatePicUrl(ossKey);
        model.setUploaderId(account.getSupervisorId());
        model.setUploaderName(account.getLoginUser());
        model.setUploadTm(new Date());
        dtHealthManageInstitutionService.savePrescriptionTemplate(model);
        return map;
    }


    @RequestMapping("institutionalInfo/selectedPrescriptionTemplate")
    @ResponseBody
    Map<String, Object> selectedPrescriptionTemplate(HttpSession session, @RequestParam Integer[] templateIds, @RequestParam String institutionId) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        dtHealthManageInstitutionService.deletePrescriptionTemplate(institutionId);
        for (int i = 0; i < templateIds.length; i++) {
            DtPrescriptionTemplateManageModel model = dtHealthManageInstitutionService.selectPreTempByPrimaryKey(templateIds[i]);
            model.setInstitutionId(institutionId);
            model.setId(null);
            dtHealthManageInstitutionService.savePrescriptionTemplate(model);
        }
        map.put("errCode", 1);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        return map;
    }

    @RequestMapping("institutionalInfo/getTemplatesByInstitutionId")
    @ResponseBody
    Map<String, Object> getTemplatesByInstitutionId(HttpSession session, @RequestParam String institutionId) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        List<DtPrescriptionTemplateManageModel> institutionTemplates = dtHealthManageInstitutionService.selectPrescriptionTemplate(institutionId, null);
        map.put("institutionTemplates", institutionTemplates);
        map.put("errCode", 1);
        map.put("errMsg", "成功");
        return map;
    }


    @RequestMapping(value = "institutionalInfo/downloadTemplate", method = RequestMethod.GET)
    public @ResponseBody
    void downloadTemplate(
            HttpServletResponse response, HttpServletRequest request) {
        //下载模板
        dataImportService.downloadTemplate(response, request);
    }

    @RequestMapping(value = "institutionalInfo/importExcel", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> importExcel(HttpSession session, @RequestParam("importExcelFile") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", 0);
            return map;
        }
        try {
            dataImportService.importExcel(file, account);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存信息失败,错误原因:" + e.getMessage(), e);
            map.put("errCode", 0);
            map.put("errMsg", e.getMessage());
            return map;
        }

        map.put("errCode", 1);
        map.put("errMsg", "成功");
        return map;
    }
}